package com.whisperly.echotalk.account;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.LocaleList;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.util.Log;
import android.util.Patterns;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.whisperly.echotalk.bllmodel.UserWithChat;
import com.whisperly.echotalk.starryb.R;
import com.whisperly.echotalk.starryb.schemas.Login;
import com.whisperly.echotalk.starryb.schemas.Register;
import com.whisperly.echotalk.starryb.utils.AppsManager;
import com.whisperly.echotalk.starryb.utils.DatabaseHelper;
import com.whisperly.echotalk.starryb.utils.EmailUtil;
import com.whisperly.echotalk.starryb.utils.GlobalData;
import com.whisperly.echotalk.starryb.utils.MD5Utils;

import java.util.List;
import java.util.Locale;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SQLQueryListener;
import cn.bmob.v3.listener.UpdateListener;

public class FindPassword extends AppCompatActivity {
    private Button validate,btnSendCode;
    private EditText etUserName, etEmail,verification;
    private Toast current;
    private String email,userName,userInputCode;
    private CountDownTimer countDownTimer;
    private View loadingView;
    @Override
    protected void attachBaseContext(Context newBase) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(newBase);
        String languageCode = prefs.getString("language", "en");
        super.attachBaseContext(updateResources(newBase, languageCode));
    }

    public Context updateResources(Context context, String languageCode) {
        Locale locale = new Locale(languageCode);
        Locale.setDefault(locale);

        Resources res = context.getResources();
        Configuration config = new Configuration(res.getConfiguration());
        config.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        config.setLocales(localeList);
        context = context.createConfigurationContext(config);
        return context;
    }
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_password);
        AppsManager.addActivity(this);
        etUserName = findViewById(R.id.user_name);
        etEmail = findViewById(R.id.email);
        validate = findViewById(R.id.confirm);
        btnSendCode = findViewById(R.id.btn_send_code);
        verification = findViewById(R.id.verification_code);
        loadingView = getLayoutInflater().inflate(R.layout.layout_loading, null);

        validate.setOnClickListener(v -> validateInfo());
        btnSendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = etEmail.getText().toString().trim();
                if (isValidEmail(email)){
                    startCountDown();
                    // 调用发送验证码的方法
                    EmailUtil.generateCode();
                    EmailUtil.sendEmail(email,v, FindPassword.this);
                }else {
                    etEmail.setError(getString(R.string.invalid_email_address));
                }
            }
        });
    }
    private boolean isValidEmail(String email) {
        return Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void startCountDown() {
        btnSendCode.setEnabled(false); // 禁用按钮防止重复点击
        countDownTimer = new CountDownTimer(60000, 1000) {
            public void onTick(long millisUntilFinished) {
                btnSendCode.setText(getString(R.string.resend_code_in, millisUntilFinished / 1000));
            }

            public void onFinish() {
                btnSendCode.setText(R.string.send_code);
                btnSendCode.setEnabled(true); // 重新启用按钮
            }
        }.start();
    }

    private void validateInfo(){
        showLoading();
        new Handler(Looper.getMainLooper()).postDelayed(()->{
            userName = etUserName.getText().toString().trim();
            email = etEmail.getText().toString().trim();
            userInputCode = ((EditText)findViewById(R.id.verification_code)).getText().toString().trim();

            if (userInputCode.isEmpty()) {
                if (current != null) {
                    current.cancel();
                }
                current = Toast.makeText(this, R.string.Please_enter_the_verification_code, Toast.LENGTH_SHORT);
                current.show();
                verification.setError(getString(R.string.Please_enter_the_verification_code));
                hideLoading();
                return;

            }

            if (!EmailUtil.isCodeValid()) {
                if (current != null) {
                    current.cancel();
                }
                current = Toast.makeText(this, R.string.Verification_code_has_expired, Toast.LENGTH_SHORT);
                current.show();
                verification.setError(getString(R.string.Verification_code_has_expired));
                hideLoading();
                return;
            }

            if (!userInputCode.equals(EmailUtil.getVerificationCode())) {
                if (current != null) {
                    current.cancel();
                }
                current = Toast.makeText(this, R.string.Verification_code_is_incorrect, Toast.LENGTH_SHORT);
                current.show();
                verification.setError(getString(R.string.Verification_code_is_incorrect));
                hideLoading();
                return;
            }

            BmobQuery<UserWithChat> userWithChatBmobQuery = new BmobQuery<>();
            userWithChatBmobQuery.doSQLQuery("select * from UserWithChat where name = '" + userName + "' and '" + email + "'", new SQLQueryListener<UserWithChat>() {
                @Override
                public void done(BmobQueryResult<UserWithChat> bmobQueryResult, BmobException e) {
                    if (e == null){
                        List<UserWithChat> results = bmobQueryResult.getResults();
                        if (!results.isEmpty()){
                            showResetPasswordDialog();
                            for (UserWithChat result : results) {
                                GlobalData.setUser(result.getObjectId(),result);
                                return;
                            }
                        }else {
                            if (current!=null){
                                current.cancel();
                            }

                            current = Toast.makeText(FindPassword.this, R.string.double_check, Toast.LENGTH_SHORT);
                            current.show();
                        }
                    }else {
                        Log.e("UserWithChat",e.toString());
                    }
                    hideLoading();
                }
            });
        },1000);
    }

    private void showResetPasswordDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater = getLayoutInflater();
        View dialogView = inflater.inflate(R.layout.reset_password, null);
        final EditText etNewPassword = dialogView.findViewById(R.id.et_new_password);
        final EditText etConPassword = dialogView.findViewById(R.id.et_confirm_password);

        builder.setView(dialogView)
                .setTitle(R.string.Reset_your_password)
                .setCancelable(false)
                .setPositiveButton(R.string.confirm, null)
                .setNegativeButton(R.string.cancel, (dialog, which) -> dialog.cancel());

        AlertDialog dialog = builder.create();
        dialog.setOnShowListener(dialogInterface -> {
            Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
            positiveButton.setOnClickListener(view -> {
                String newPassword = etNewPassword.getText().toString().trim();
                String conPassword = etConPassword.getText().toString().trim();

                if (newPassword.isEmpty()){
                    if (current!=null){
                        current.cancel();
                    }
                    current = Toast.makeText(this, R.string.Please_d_leave_it_blank, Toast.LENGTH_SHORT);
                    current.show();
                    etNewPassword.setError("");
                }else if (conPassword.isEmpty()){
                    if (current!=null){
                        current.cancel();
                    }
                    current = Toast.makeText(this, R.string.Please_d_leave_it_blank, Toast.LENGTH_SHORT);
                    current.show();
                    etConPassword.setError("");
                }else if (!newPassword.equals(conPassword)){
                    if (current!=null){
                        current.cancel();
                    }
                    current = Toast.makeText(this, R.string.The_password_is_inconsisten_twice, Toast.LENGTH_SHORT);
                    current.show();
                    etConPassword.setError(getString(R.string.The_password_is_inconsisten_twice));
                }else {

                    resetUserPassword(newPassword);
                    dialog.dismiss();
                }
            });
        });
        dialog.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }
    private void resetUserPassword(String newPassword) {
        newPassword = MD5Utils.stringMD5(newPassword);
        UserWithChat user = GlobalData.getUser();
        user.setPassword(newPassword);
        user.update(user.getObjectId(), new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null){
                    if (current!=null){
                        current.cancel();
                    }
                    current = Toast.makeText(FindPassword.this, R.string.New_password_set_successfully, Toast.LENGTH_SHORT);
                    current.show();
                    Intent intent = new Intent(FindPassword.this, Login.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                    finish();
                }else {
                    Log.e("e",e.toString());
                }
            }
        });
    }

    private void showLoading() {
        if (loadingView.getParent() == null) {
            ((ViewGroup) findViewById(android.R.id.content)).addView(loadingView);
            Log.d("LoginActivity", "Loading view added");
        }
    }

    private void hideLoading() {
        ((ViewGroup) findViewById(android.R.id.content)).removeView(loadingView);
    }
}
